package cn.yomigaeri.signal.task;

import cn.yomigaeri.common.entity.dto.SignalDTO;
import cn.yomigaeri.common.json.JacksonObjectMapper;
import cn.yomigaeri.signal.producer.SignalProducer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @ClassName: WarnAllSignalTask
 * @Package: cn.yomigaeri.signal.task
 * @Description:
 * @Author Yomigaeri
 * @Create 2025/6/5 11:53
 * @Version 1.0
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class WarnAllSignalTask {
    private final RedisTemplate<String, Object> redisTemplate;
    private final SignalProducer  signalProducer;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void warnAllSignal() {
        // 获取所有以 "SignalOfCarId:" 为前缀的键
        String keyPattern = "SignalOfCarId:*";
        Set<String> keys = scanKeys(keyPattern);

        if (!keys.isEmpty()) {
            for (String key : keys) {
                // 获取每个键对应的值
                Object obj = redisTemplate.opsForValue().get(key);
                if (obj instanceof Map) {
                    signalProducer.sendCheckMessage(new JacksonObjectMapper().convertValue(obj, SignalDTO.class));
                }
            }
        } else {
            log.error("SignalOfCarId为空");
        }
    }

    private Set<String> scanKeys(String pattern) {
        Set<String> keys = new HashSet<>();
        redisTemplate.execute((RedisConnection connection) -> {
            try (Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions().match(pattern).build())) {
                cursor.forEachRemaining(item -> keys.add(new String(item, StandardCharsets.UTF_8)));
            }
            return null;
        });
        return keys;
    }
}

